//index.js
var util = require('../../utils/util')

const app = getApp()

Page({
  data: {
    ScrollHeight: 0,   //滚动区域的高度
    location: '加载中...',
    list: [],
    weatherlist: [],
    nowdata: '加载中',
    time: '',
    today: '',
    city: '',
  },

  onLoad: function () {
    var loc = this;   //设置当地位置天气等信息的指针


    setInterval(function () {   //显示时间，1s定时器工作一次
      loc.setData({
        time: util.formatTime(new Date())
      });
    }, 1000);
    this.CalculateScrollHeight(); //获取当前机型滚动屏幕区域的高度

    wx.getLocation({  //获取经度纬度
      type: 'gcj02',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        console.log(latitude, longitude)  //当前经纬度
        wx.request({    //使用腾讯地图逆地址解析接口
          url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=IXPBZ-SFZH3-5VN33-YSKNH-NWIG7-WMFKF&get_poi=1',
          header: {
            'content-type': 'application/json' // 默认值
          },
          success: function (res) {
            loc.setData({
              city: res.data.result.ad_info.city,
              location: res.data.result.ad_info.city + res.data.result.ad_info.district//设置当前位置，“城市+区”
            })
            console.log(loc.data.city);  //获取当前的市
            console.log(res.data.result.ad_info.city_code) //对应的码
            wx.request({
              url: 'https://free-api.heweather.net/s6/weather/forecast?location=' + res.data.result.ad_info.city + '&key=10a734a0b2b340d0a4cc5c87a433b968',//使用和风天气api，获取最近七天的天气信息
              header: {
                'content-type': 'application/json' // 默认值
              },
              success(res) {

                loc.setData({
                  weatherlist: loc.getWeatherList(res.data.HeWeather6[0].daily_forecast),   //获取到近七天的列表
                  
                })
                console.log(res.data.HeWeather6[0].daily_forecast)  //显示未来七天天气

                wx.request({
                  url: 'https://free-api.heweather.net/s6/weather/now?location=' + res.data.HeWeather6[0].basic.location + '&key=10a734a0b2b340d0a4cc5c87a433b968', //使用和风天气api，获取实时天气信息
                  header: {
                    'content-type': 'application/json' // 默认值
                  },
                  success(res) {
                    loc.getNowCodeImg(res.data.HeWeather6[0].now);    //使用方法将当前的天气码转换为图片地址
                    console.log(res.data.HeWeather6[0].now)//显示实况天气
                  }
                })
              }
            })
          }
        })
      }
    })
  },
  search: function (event) {
    var loc = this;   //设置当地位置天气等信息的指针
    setInterval(function () {   //显示时间，1s定时器工作一次
      loc.setData({
        time: util.formatTime(new Date())
      });
    }, 1000);
    this.CalculateScrollHeight(); //获取当前机型滚动屏幕区域的高度
    wx.request({
      url: 'https://free-api.heweather.net/s6/weather/forecast?location=' + loc.data.city + '&key=10a734a0b2b340d0a4cc5c87a433b968',//使用和风天气api，获取最近七天的天气信息
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        loc.setData({
          weatherlist: loc.getWeatherList(res.data.HeWeather6[0].daily_forecast),   //获取到近七天的列表
          location: loc.data.city,
        })
        console.log(res.data.HeWeather6[0])
        wx.request({
          url: 'https://free-api.heweather.net/s6/weather/now?location=' + loc.data.city + '&key=10a734a0b2b340d0a4cc5c87a433b968', //使用和风天气api，获取实时天气信息
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res) {
            loc.getNowCodeImg(res.data.HeWeather6[0].now);    //使用方法将当前的天气码转换为图片地址
          }
        })
      }
    })
  },
  bindKeyInput: function (event) {
    var val = event.detail.value;
    this.setData({
      city: val
    })
  },
  CalculateScrollHeight() {    //计算滚动条起始高度（不能固定死）
    let that = this;
    let query = wx.createSelectorQuery().in(this);
    query.select('.top').boundingClientRect(function (res) {
      let TopHeight = res.height;
      let ScreenHeight = wx.getSystemInfoSync().windowHeight;
      let ScrollHeight = ScreenHeight - TopHeight - 70;     //分别获取到全屏高度与上半部分高度，都减掉才是下面滚动条的起始高度，70是最上面title的高度
      that.setData({
        ScrollHeight: ScrollHeight
      })
    }).exec();
  },
  getNowCodeImg(now) {    //获取实时信息的图片
    now.cond_code_img = "/images/cond-icon-heweather/" + now.cond_code + ".png";
    this.setData({
      nowdata: now
    })
  },
  getWeatherList(data) {   //从全部信息中获取我们需要的信息，组成一个新list
    let listdata = [];
    let today = '';
    for (let i = 0; i < data.length; i++) {
      data[i].weekday = this.getWeekday(data[i].date);
      data[i].icon = this.getweatherIcon(data[i].cond_code_d);
      data[i].weatherinfo = this.getWeatherInfo(data[i].cond_code_d);
      if (i != 0) {
        listdata.push(data[i]);
      } else {
        today = data[i].weekday = this.getWeekday(data[i].date);
      }
    }
    this.setData({
      list: listdata,
      today: today,
    })
    return this.data.list;
  },
  getWeekday(date) {   //把日期转化为星期
    var myDay = new Date(date);
    var myddy = myDay.getDay();   //获取到对应星期几的数字
    var weekday = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]; //下表从零开始，也就是星期日要在最前面
    return weekday[myddy];  //返回对应的星期
  },

  getweatherIcon(code) {   //通过code获取到对应的天气图片
    switch (code) {
      case '100':
        return '/images/cond-icon-heweather/100.png';
      case '101':
        return '/images/cond-icon-heweather/101.png';
      case '102':
        return '/images/cond-icon-heweather/102.png';
      case '103':
        return '/images/cond-icon-heweather/103.png';
      case '104':
        return '/images/cond-icon-heweather/104.png';
      case '200':
        return '/images/cond-icon-heweather/200.png';
      case '201':
        return '/images/cond-icon-heweather/201.png';
      case '202':
        return '/images/cond-icon-heweather/202.png';
      case '203':
        return '/images/cond-icon-heweather/203.png';
      case '204':
        return '/images/cond-icon-heweather/204.png';
      case '205':
        return '/images/cond-icon-heweather/205.png';
      case '300':
        return '/images/cond-icon-heweather/300.png';
      case '301':
        return '/images/cond-icon-heweather/301.png';
      case '302':
        return '/images/cond-icon-heweather/302.png';
      case '303':
        return '/images/cond-icon-heweather/303.png';
      case '304':
        return '/images/cond-icon-heweather/304.png';
      case '305':
        return '/images/cond-icon-heweather/305.png';
      case '306':
        return '/images/cond-icon-heweather/306.png';
      case '307':
        return '/images/cond-icon-heweather/307.png';
      case '308':
        return '/images/cond-icon-heweather/308.png';
      case '309':
        return '/images/cond-icon-heweather/309.png';
      case '310':
        return '/images/cond-icon-heweather/310.png';
      default: return '/images/cond-icon-heweather/000.png';
    }
  },

  getWeatherInfo(code) {   //通过code获取对应的天气信息
    switch (code) {
      case '301':
        return '强阵雨';
      case '302':
        return '雷阵雨';
      case '303':
        return '强雷阵雨';
      case '304':
        return '雷阵雨伴有冰雹';
      case '305':
        return '小雨';
      case '306':
        return '中雨';
      case '307':
        return '大雨';
    }
  }
})
